/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.actions;

import opiam.admin.applis.demo.beans.Department;

import opiam.admin.faare.SearchResult;
import opiam.admin.faare.persistence.javabeans.JBTop;
import opiam.admin.faare.service.UserContext;
import opiam.admin.faare.service.javabeans.Criteria;
import opiam.admin.faare.service.javabeans.SearchArgument;
import opiam.admin.faare.service.services.StandardService;
import opiam.admin.faare.struts.actions.SecureAction;
import opiam.admin.faare.struts.utils.SessionContext;

import org.apache.log4j.Logger;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * This class allows to show a department entry.
 *
 * This Action class inherits from SecureAction class.
 * The SecureAction class checks that the user is connected before calling
 * the action methods.
 */
public class ShowDepartmentAction extends SecureAction
{
    /** Instance of the log4j logger.
     * Used to generate the execution traces. */
    private static Logger _logger =
        Logger.getLogger(ShowDepartmentAction.class);

    /**
     * This method is called to execute the action once the checks have been
     * performed by the SecureAction class.
     *
     * @param mapping              Struts mapping data.
     * @param actionForm           FormBean associated with the action.
     * @param request              HTTP request.
     * @param httpServletResponse  HTTP response.
     *
     * @return An ActionForward.
     *
     * @throws IOException  An I/O exception if failed or interrupted I/O operations occurs.
     * @throws ServletException  A ServletException if the servlet has a problem.
     */
    @Override
	public ActionForward secureExecute(ActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse httpServletResponse
                                      ) throws IOException, ServletException
    {
        SessionContext sessionContext = null;
        UserContext userContext = null;
        ActionMessages msgErrors = new ActionMessages();

        try
        {
            // Gets the session.
            HttpSession session = request.getSession();

            // Gets the session context.
            sessionContext = SessionContext.getInstance(session);

            // Gets the user context.
            userContext = sessionContext.getUserContext();

            // Gets the entry rdn from the request.
            String rdn = request.getParameter("dn");

            if (rdn != null)
            {
                Criteria c1 = Criteria.getAndInstance();
                c1.addEqualsTo("ou", rdn);

                SearchArgument arg =
                    new SearchArgument(c1,
                                       userContext.findJBRessourceByName("department"),
                                       userContext
                                      );
                List args = new ArrayList();
                args.add(arg);

                SearchResult resEntries =
                    StandardService.search(args, userContext);

                Iterator it = resEntries.getLResults().iterator();

                Department department = null;

                while (it.hasNext())
                {
                    JBTop entry = (JBTop) it.next();

                    if (entry instanceof Department)
                    {
                        department = (Department) entry;
                    }
                }

                _logger.info("Show department : " + department.getDn() +
                             " by user: " +
                             sessionContext.getUserContext().getDn()
                            );

                // Sets the Bean in the session with the "currentDepartment" name.
                // This name is used in the jsp page by the Struts tags to
                // recover the attributes values of the department entry.  
                session.setAttribute("currentDepartment", department);

                // Returns the URI corresponding to the action success
                // as defined in the action configuration in the struts-config.xml.
                return mapping.findForward("success");
            }
            else
            {
                throw new Exception("Null argument");
            }
        }
        catch (Exception se)
        {
            se.printStackTrace();
            _logger.error(se.getMessage());
            msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                          new ActionMessage("error.service.unknown")
                         );
            saveErrors(request, msgErrors);

            return (mapping.findForward("error"));
        }
    }
}
